package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMessage;
import com.ccp.dev.qbdms.model.WQbdQuasuporgBase;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.service.WQbdQuasuporgBaseService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.service.DictionaryService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 质量技术支撑机构 信息操作处理控制器
 * 
 * @author y
 * @date 2020-07-06 20:12:54
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "质量技术支撑机构")
@RequestMapping("/qbdms/wQbdQuasuporgBase")
public class WQbdQuasuporgBaseController extends SysBaseController{
	@Resource
	private WQbdQuasuporgBaseService wQbdQuasuporgBaseService;
	@Resource
	private DictionaryService dictionaryService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: y
     * @date: 2020-07-06 20:12:54
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到质量技术支撑机构首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request,ModelMap model) {
        wCustomColumnsService.addCustomCols(request);
        model.put("currentSystemLevel", BaseUtil.getCurrentSystemLevel());
        model.put("userId", ContextUtil.getCurrentUserId());
        return "wQbdQuasuporgBase/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: y
    * @date: 2020-07-06 20:12:54
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询质量技术支撑机构",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request){
        QueryFilter queryFilter = new QueryFilter(request, true);
        //分页数据
        ZhiLiangConst.addQueryFilter(queryFilter);
        if(BeanUtils.isEmpty(queryFilter.get("orderField"))){
            queryFilter.addFilter("orderField","reply_time");
            queryFilter.addFilter("orderSeq","desc");
        }
        List<WQbdQuasuporgBase> pageDatas = wQbdQuasuporgBaseService.queryList(queryFilter);
        ZhiLiangConst.isDataAllowEdit(pageDatas,false);
        try {
            ZhiLiangConst.showName(pageDatas);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: y
     * @date: 2020-07-06 20:12:54
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到质量技术支撑机构新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        // 上传附件类型相关
        String zljzzcjgfjszlxkz = PropertyUtil.getByAlias("zljzzcjgfjszlxkz", "");
        modelMap.put("uploadType", zljzzcjgfjszlxkz);
        String selectType = PropertyUtil.getByAlias("zljzzcjgszwjlxsx", "");
        modelMap.put("selectType", selectType);
        //数据字典
        Map<String,String> ccrdMap = new LinkedHashMap<>();
        Map<String,String> rdyqMap = new LinkedHashMap<>();
        List<Dictionary>  ccrds = dictionaryService.getByNodeKey("ccrd");
        ccrds.forEach(a->{
            ccrdMap.put(a.getItemValue(),a.getItemName());
        });
        List<Dictionary>  rdyqs = dictionaryService.getByNodeKey("rdyq");
        rdyqs.forEach(a->{
            rdyqMap.put(a.getItemValue(),a.getItemName());
        });
        modelMap.put("ccrds", com.alibaba.fastjson.JSONObject.toJSONString(ccrdMap));
        modelMap.put("rdyqs", com.alibaba.fastjson.JSONObject.toJSONString(rdyqMap));
        return "wQbdQuasuporgBase/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdQuasuporgBase 保存的对象
    * @return: java.lang.Object
    * @auther: y
    * @date: 2020-07-06 20:12:54
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存质量技术支撑机构数据",detail="<#if isAdd>新增<#else>编辑</#if>质量技术支撑机构数据<#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if><#if success>成功<#else>失败</#if>")
    public Object save(@RequestBody WQbdQuasuporgBase wQbdQuasuporgBase) {
        String id = wQbdQuasuporgBase.getId();
        SysAuditThreadLocalHolder.putParamerter("success",false);
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
        }else{
            WQbdQuasuporgBase oldModel = wQbdQuasuporgBaseService.getOneById(id);
            String modifyInfo = StructureModifyUtil.getModifyInfo(oldModel,wQbdQuasuporgBase);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo",modifyInfo);
        }
        wQbdQuasuporgBaseService.save(wQbdQuasuporgBase);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("save.success");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: y
    * @date: 2020-07-06 20:12:54
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到质量技术支撑机构详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        boolean isClose = RequestUtil.getBoolean(request,"isClose",false);
        modelMap.put("id",id);
        modelMap.put("isClose",isClose);
        return "wQbdQuasuporgBase/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: y
    * @date: 2020-07-06 20:12:54
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询质量技术支撑机构的一条数据",detail="根据主键id查询质量技术支撑机构的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdQuasuporgBase wQbdQuasuporgBase = wQbdQuasuporgBaseService.getAllData(id);
        if (null == wQbdQuasuporgBase) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdQuasuporgBase);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: y
    * @date: 2020-07-06 20:12:54
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除质量技术支撑机构数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdQuasuporgBase wQbdQuasuporgBase = this.wQbdQuasuporgBaseService.getOneById(key);
            if (!userId.equals(wQbdQuasuporgBase.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            if (Objects.nonNull(wQbdQuasuporgBase.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdQuasuporgBase.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdQuasuporgBase.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报和待报集团的数据");
            }
        }
        SysAuditThreadLocalHolder.putParamerter("success",false);
        wQbdQuasuporgBaseService.delByIds(id.split(","));
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("delete.success");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到质量技术支撑机构导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdQuasuporgBase/import";
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description="跳转到质量技术支撑机构选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request,ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdQuasuporgBase.class);
        modelMap.put("tableInfo",jsonObject.toString());
        return "expImp/add";
    }

    /**
     * 功能描述: 导出质量技术支撑机构管理数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2020-07-06 14:10:36
     */
    @RequestMapping("/exportData")
    @Action(description="导出质量技术支撑机构管理数据信息",detail="导出质量技术支撑机构管理数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success",false);
        String[] id = RequestUtil.getStringAryByStr(request,"id");
        QueryFilter queryFilter = new QueryFilter(request,false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter,id);
        queryFilter.addFilter("belongdeptname", BaseUtil.getCurrentTenOrgCodePath() + "%");
        List<WQbdQuasuporgBase> wQbdQuasuporgBase = this.wQbdQuasuporgBaseService.queryAll(queryFilter);
        if(wQbdQuasuporgBase.isEmpty()){
            wQbdQuasuporgBase.add(new WQbdQuasuporgBase());
        }

        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request,response,wQbdQuasuporgBase,dataArray,"质量技术支撑机构管理信息", AbstractExpUtil.ExpStyle.MANY_SHEET);

        SysAuditThreadLocalHolder.putParamerter("success",true);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success",false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdQuasuporgBase.class);
        String msg = map.get("msg").toString();
        List<WQbdQuasuporgBase> list = (List<WQbdQuasuporgBase>)map.get("instList");
        if(StringUtil.isEmpty(msg)){
            this.wQbdQuasuporgBaseService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("dataSource.importXml.success");
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail(msg);
        }
    }
    /**
     * 查询上报的信息
     *
     * @param request HttpServletRequest
     * @param id 主数据id
     * @param tableName 表名
     * @return obj
     */
    @RequestMapping("/reportList")
    @ResponseBody
    @Action(description = "查询上报的信息")
    public Object reportList(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<WQbdQuasuporgBase> reportList = wQbdQuasuporgBaseService.reportList(id, tableName);
        ZhiLiangConst.showName(reportList);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }
}
